<template>
  <Form class="xtx-form" ref="formCom" :validation-schema="veeValidateSchema" v-slot="{ errors }">
    <h3>{{errors}}</h3>
    <div class="user-info">
      <img :src="avatar" alt="" />
      <p>Hi，{{nickname}} 欢迎来小兔鲜，完成绑定后可以QQ账号一键登录哦~</p>
    </div>
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-phone"></i>
        <Field name="mobile" v-model="form.mobile" class="input" type="text" placeholder="绑定的手机号" />
      </div>
      <div class="error" v-if="errors.mobile">{{errors.mobile}}</div>
    </div>
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-code"></i>
        <Field name="code" v-model="form.code" class="input" type="text" placeholder="短信验证码" />
        <span class="code" @click="sendCodeBtn">{{number===0?'发送验证码':number+'秒后发送'}}</span>
      </div>
      <div class="error" v-if="errors.code">{{errors.code}}</div>
    </div>
    <a href="javascript:;" class="submit" @click="loginBtn">立即绑定</a>
  </Form>
</template>

<script>
import { Field, Form } from 'vee-validate'
import { reactive, ref, watch } from 'vue'
import veeValidateSchema from '@/utils/vee-validate-schema'
import { userQQBindCode, userQQBindLogin } from '@/api/user'
import { login, sendCode } from '@/utils/formbtn'
export default {
  name: 'CallbackBind',
  components: {
    Field, Form
  },
  props: {
    unionId: {
      type: String,
      default: ''
    }
  },
  setup (props) {
    const nickname = ref('')
    const avatar = ref('')
    if (QC.Login.check()) {
      // 获取QQ用户的头像和昵称展示  QC.api('get_user_info').success
      // 业务1：获取用户公开信息
      QC.api('get_user_info').success(({ data }) => {
        console.log(data)
        nickname.value = data.nickname
        avatar.value = data.figureurl_1
      })
    }
    // 业务2：获取表单数据和表单校验
    const form = reactive({
      unionId: '',
      mobile: '',
      code: ''
    })

    watch(() => props.unionId, () => {
      form.unionId = props.unionId
    }, { immediate: true })

    const formCom = ref(null)

    // 业务3：发送验证码事件
    const number = ref(0)

    const sendCodeBtn = () => {
      // 发送验证码封装的函数
      sendCode(userQQBindCode, form.mobile, formCom, number)
    }

    // 业务4：立即绑定点击事件
    const loginBtn = () => {
      login(userQQBindLogin, form, formCom)
    }

    return { nickname, avatar, form, veeValidateSchema, number, formCom, sendCodeBtn, loginBtn }
  }
}
</script>

<style scoped lang='less'>
.user-info {
    width: 320px;
    height: 70px;
    margin: 0 auto;
    display: flex;
    background: #f2f2f2;
    align-items: center;
    padding: 0 10px;
    margin-bottom: 25px;
    img {
      background: #f2f2f2;
      width: 50px;
      height: 50px;
    }
    p {
      padding-left: 10px;
    }
  }
  .code {
    position: absolute;
    right: 0;
    top: 0;
    line-height: 50px;
    width: 80px;
    color: #999;
    &:hover {
      cursor: pointer;
    }
  }
</style>
